<template>
  <div class="app-container">
    <page-search ref="searchRef" :search-config="searchConfig" @query-click="handleQueryClick"
      @reset-click="handleResetClick" />
    <PageContent ref="contentRef" :gridOptions="gridOptions" :content-config="contentConfig" @addClick="handleAddClick"
      @edit-click="handleEditClick" @export-click="handleExportClick" @toolbarClick="handleToolbarClick"
      @operat-click="handleOperatClick">
      <template #status="scope">
        <el-tag :type="statusType[scope.row[scope.prop]]">
          {{ $t(`withdrawStatus.${scope.row[scope.prop]}`) }}
        </el-tag>
      </template>
      <template #tool="scope">
        <!-- <template v-if="[0,2].includes(scope.row.status)"> -->
        <!-- <template v-if="scope.row.admin_id ===0 || scope.row.admin_id === userStore.user.id ">
            <el-button size="small" :type="scope.row.locked?'warning':'danger'" link @click="toolClick('locked',scope)">
              {{$t(scope.row.locked ? "status.14" : "status.15") }}
            </el-button>
          </template>
<template v-else>
            <el-button size="small" type="warning" link disabled>
              {{$t('status.16')}}
            </el-button>
          </template> -->
        <template v-if="scope.row.status==='pending'">
          <el-button size="small" type="success" link @click="toolClick('approve',scope)">
            {{$t('oper.10')}}
          </el-button>
          <el-button size="small" type="danger" link @click="toolClick('reject',scope)">
            {{$t('oper.11')}}
          </el-button>
        </template>
        <template v-if="scope.row.status==='approved'">
          <el-button size="small" type="success" link @click="toolClick('process',scope)">
            {{$t('status.18')}}
          </el-button>
          <template v-if="scope.row.admin_id === userStore.user.id">
            <el-button size="small" type="success" link @click="toolClick('revoke',scope)">
              {{$t('oper.12')}}
            </el-button>
          </template>

          <el-button size="small" type="warning" link @click="toolClick('complete',scope)">
            {{$t('status.47')}}
          </el-button>
        </template>
        <template v-if="scope.row.status==='processing'">
          <template v-if="scope.row.locked">
            <el-button size="small" type="danger" link @click="toolClick('reject',scope)">
              {{$t('oper.11')}}
            </el-button>
          </template>
        </template>
      </template>
    </PageContent>
  </div>
</template>

<script setup>
import searchConfig from "./config/search";
import contentConfig from "./config/content";
import usePage from "@/hooks/usePage";
import { onMounted } from "vue";
import Api from '@/api/finance/withdraw'
import ComApi from '@/api/common'
import { useUserStore } from "@/stores";
import { tableHeightAutoAdjust } from '@/utils/common'
defineOptions({
  name: "financeWithdraw",
  inheritAttrs: false,
});

const { t } = useI18n();
const userStore = useUserStore();

const gridOptions = reactive({})

const statusType = {
  "pending": "primary",
  "approved": "success",
  "rejected": "danger",
  "processing": "warning",
  "completed": "success",
  "failed": "danger"
}

const { searchRef, contentRef, addModalRef, editModalRef,
  handleQueryClick, handleResetClick, handleAddClick,
  handleSubmitClick, handleExportClick, } = usePage();
const handleEditClick = (row) => {
  // 模拟根据id获取数据进行填充
  editModalRef.value?.setModalVisible(row);
}
const logInfoRef = ref(null)
const handleOperatClick = (obj) => {
  if (obj.name === "details") {
    logInfoRef.value.show(obj.row.id)
  }
}
const toolClick = (type, { row }) => {
  if (type === 'approve') {
    // 批准
    approveFn(row.id)
  } else if (type === 'reject') {
    // 拒绝
    rejectFn(row.id)
  } else if (type === 'revoke') {
    // 撤销批准
    revokeFn(row.id)
  } else if (type === 'process') {
    // 代付
    processFn(row.id)
  } else if (type === 'complete') {
    // 强制出款
    completeFn(row.id)
  }
}
// 批准
const approveFn = (id) => {
  ElMessageBox.confirm(t('hint.91')).then(() => {
    Api.approve(id).then(s => {
      ElMessage({
        type: 'success',
        message: t('hint.92'),
      })
      handleSubmitClick()
    })
  }).catch(() => { })
}
// 
// 撤销批准
const revokeFn = (id) => {
  ElMessageBox.confirm(t('hint.93')).then(() => {
    console.log('112233=======');

    Api.revoke(id).then(s => {
      ElMessage({
        type: 'success',
        message: t('hint.94'),
      })
      handleSubmitClick()
    })
  }).catch(() => { })
}
// 拒绝
const rejectFn = (id) => {
  ElMessageBox.prompt(t('hint.95'), t('hint.1'), {
    inputPattern: /\S/,
    inputErrorMessage: t('hint.96'),
  }).then(({ value }) => {
    console.log(value);
    Api.reject(id, { note: value }).then(s => {
      ElMessage({
        type: 'success',
        message: t('hint.16'),
      })
      handleSubmitClick()
    })
  })
}
// 代付
const processFn = (id) => {
  ElMessageBox({
    title: t('hint.1'),
    message: () => h('div', {}, [
      h('p', { style: "margin-bottom: 20px" }, t('hint.17')),
      h(ElSelect, {
        style: 'width: 200px',
        modelValue: selectedValue.value,
        multiple: false, // 多选
        'onUpdate:modelValue': (val) => {
          selectedValue.value = val
        }
      }, selectOptions.value),
    ])
  }).then(action => {
    // 处理用户点击确定或取消按钮后的逻辑
    console.log('action', action)
    if (action === 'confirm') {
      Api.process(id, { payment_method_id: selectedValue.value }).then(s => {
        console.log('代付返回值====>',s)
        ElMessage({
          type: 'success',
          message: t('hint.18'),
        })
        handleSubmitClick()
      }).catch(err => {
        if(err.status === 500) { 
          ElMessage.error(t('hint.161'))
        }
      })
    }
  })
}
const completeFn = (id) => {
  ElMessageBox.confirm(t('hint.97')).then(() => {
    Api.complete(id).then(s => {
      ElMessage({
        type: 'success',
        message: t('hint.98'),
      })
      handleSubmitClick()
    })
  })
}

// 锁定 解锁
const lockedFn = (id, bo) => {
  ElMessageBox.confirm('确认批准该用户提款?').then(() => {
    if (bo) {
      Api.unlock(id).then(s => {
        ElMessage({
          type: 'success',
          message: t('hint.12'),
        })
        // handleQueryClick()
        handleSubmitClick()
      })
    } else {
      Api.lock(id).then(s => {
        ElMessage({
          type: 'success',
          message: t('hint.13'),
        })
        handleSubmitClick()
      })
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: 'Delete canceled',
    })
  })


}
// 驳回
const refuseFn = (id) => {
  ElMessageBox.prompt(t('hint.14'), t('hint.1'), {
    inputPattern: /\S/,
    inputErrorMessage: t('hint.15'),
  }).then(({ value }) => {
    console.log(value);
    Api.deny(id, { note: value }).then(s => {
      ElMessage({
        type: 'success',
        message: t('hint.16'),
      })
      handleSubmitClick()
    })

  })
}
// 代付
const agreeFn = (id) => {
  ElMessageBox({
    title: t('hint.1'),
    message: () => h('div', {}, [
      h('p', { style: "margin-bottom: 20px" }, t('hint.17')),
      h(ElSelect, {
        style: 'width: 200px',
        modelValue: selectedValue.value,
        multiple: false, // 多选
        'onUpdate:modelValue': (val) => {
          selectedValue.value = val
        }
      }, selectOptions.value),
    ])
  }).then(action => {
    // 处理用户点击确定或取消按钮后的逻辑
    console.log('action', action)
    if (action === 'confirm') {
      Api.send(id, { payment_method_id: selectedValue.value }).then(s => {
        ElMessage({
          type: 'success',
          message: t('hint.18'),
        })
        handleSubmitClick()
      })
    }

  })
}
// 强制出款
// const approveFn = (id) => {
//   ElMessageBox({
//     title: t('hint.1'),
//     message: () => h('div', {}, [
//       h('p', { style: "margin-bottom: 20px" }, t('hint.86')),
//       h(ElSelect, {
//         style: 'width: 200px',
//         modelValue: approveValue.value,
//         multiple: false, // 多选
//         'onUpdate:modelValue': (val) => {
//           approveValue.value = val
//         }
//       }, selectOptions.value),
//     ])
//   }).then(action => {
//     // 处理用户点击确定或取消按钮后的逻辑
//     console.log('action', action)
//     if (action === 'confirm') {
//       // Api.approve(id).then(s => {
//       //   console.log(s);

//       // })
//       Api.approve(id, { payment_method_id: approveValue.value }).then(s => {
//         ElMessage({
//           type: 'success',
//           message: t('hint.18'),
//         })
//         handleSubmitClick()
//       })
//     }

//   })

// }
const approveValue = ref(1)
const selectedValue = ref(1)
const selectOptions = ref([])
const getPay = () => {
  ComApi.payment().then(({ data }) => {
    for (let i in data) {
      const item = data[i]
      selectOptions.value.push(h(ElOption, { label: item.name, value: item.id }))
    }
  })
}
onMounted(() => {
  getPay()
  // 确保在组件挂载后立即设置高度
  tableHeightAutoAdjust(gridOptions);
})
</script>